<script>
	import config from './config'
	import store from '@/store'
	import {
		getToken
	} from '@/utils/auth'
	import {
		getVersion
	} from '@/api/cms/cms'
	import { showConfirm } from '@/utils/common'
	export default {
		onLaunch: function() {
			this.initApp()
		},
		methods: {
			// 初始化应用
			initApp() {
				// 初始化应用配置
				this.initConfig()
				// #ifdef APP
				this.checkVersion()
				// #endif
				
				// 检查用户登录状态
				// //#ifdef H5
				// this.checkLogin()
				// //#endif

			},
			initConfig() {
				this.globalData.config = config
			},
			checkLogin() {
				if (!getToken()) {
					this.$tab.reLaunch('/pages/list/list')
				}
			},
			async checkVersion() {
				try {
					getVersion().then(res => {
						console.log("getVersion:" + JSON.stringify(res))
						console.log("appInfo.version:" + config.appInfo.version)
						console.log(res.data > config.appInfo.version)
						if (res.data > config.appInfo.version) {
							showConfirm('有新版本，是否更新?').then(res => {
							  this.downloadApk("http://images.fyliu.cn/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/game.apk")
							})
							
						}
					})
				} catch (error) {
					console.log("版本检查失败")
				}
			},
			
			// 下载APK文件
			async downloadApk(url) {
				this.showProgress = true

				this.downloadTask = uni.downloadFile({
					url: url,
					success: (res) => {
						if (res.statusCode === 200) {
							this.installApk(res.tempFilePath)
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						})
						this.resetState()
					}
				})

				this.downloadTask.onProgressUpdate((res) => {
					this.downloadPercent = res.progress
				})
			},

			// 安装APK（仅Android）
			installApk(filePath) {
				if (uni.getSystemInfoSync().platform === 'android') {
					plus.runtime.install(filePath, {
						force: false
					}, () => {
						uni.showToast({
							title: '安装完成'
						})
						plus.runtime.restart()
					}, (err) => {
						uni.showToast({
							title: '安装失败',
							icon: 'none'
						})
					})
				}
			},

			// 打开应用商店
			openAppStore() {
				// iOS示例（需要配置对应的App Store链接）
				plus.runtime.launchApplication({
					action: 'itms-apps://itunes.apple.com/app/idYOUR_APP_ID'
				}, (e) => {
					console.error('打开App Store失败:', e)
				})
			}
		}
	}
</script>

<style lang="scss">
	@import '@/static/scss/index.scss'
</style>